package com.homestay.controller;

import com.google.gson.Gson;
import com.homestay.beans.Admins;
import com.homestay.service.AdminsService;
import com.homestay.service.impl.AdminsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/admins")
public class AdminsServlet extends HttpServlet {

    AdminsService adminsService = new AdminsServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 设置请求编码,防止乱码
        req.setCharacterEncoding("utf-8");
        // 设置响应内容类型,防止乱码
        resp.setContentType("text/html;charset=utf-8");
        //System.out.println("servlet开始服务......");
        String action = req.getParameter("action");
        switch (action) {
            case "login":
                login(req, resp);
                break;
            case "logout":
                logout(req, resp);
                break;
            case "register":
                register(req, resp);
                break;
            default:
                break;
        }
    }

    private void register(HttpServletRequest req, HttpServletResponse resp) {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String againPassword = req.getParameter("againPassword");
        String usercode = req.getParameter("usercode");
        if (!password.equals(againPassword)) {
            try {
                Map<String, Object> map = new HashMap<>();
                map.put("username", username);
                map.put("password", password);
                map.put("againPassword", againPassword);
                map.put("usercode", usercode);
                map.put("msg", "两次密码不一致");
                Gson gson = new Gson();
                String json = gson.toJson(map);
                resp.getWriter().write(json);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            Admins admins = adminsService.queryByUsername(username);
            if (admins != null) {
                try {
                    Map<String, Object> map = new HashMap<>();
                    map.put("username", username);
                    map.put("password", password);
                    map.put("againPassword", againPassword);
                    map.put("usercode", usercode);
                    map.put("msg", "用户名已存在");
                    Gson gson = new Gson();
                    String json = gson.toJson(map);
                    resp.getWriter().write(json);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                // 检查会话中是否存在验证码
                HttpSession session = req.getSession();
                Object sessionSyscodeObj = session.getAttribute("syscode");
                // 验证码不存在或输入的验证码与会话中的验证码不匹配
                if (sessionSyscodeObj == null || !usercode.equalsIgnoreCase(sessionSyscodeObj.toString())) {
                    // 验证码错误
                    try {
                        // 设置错误信息
                        Map<String, Object> map = new HashMap<>();
                        map.put("username", username);
                        map.put("password", password);
                        map.put("againPassword", againPassword);
                        map.put("usercode", usercode);
                        map.put("msg", "验证码错误");
                        Gson gson = new Gson();
                        String json = gson.toJson(map);
                        resp.getWriter().write(json);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    // 验证码正确，继续注册
                    Admins admin = new Admins();
                    admin.setUsername(username);
                    admin.setPassword(password);
                    int count = adminsService.add(admin);
                    if(count > 0){
                        try {
                            Map<String, Object> map = new HashMap<>();
                            map.put("msg", "注册成功");
                            map.put("redirect","/login.jsp");
                            Gson gson = new Gson();
                            String json = gson.toJson(map);
                            resp.getWriter().write(json);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 获取用户输入的验证码
        String usercode = req.getParameter("usercode");
        // 检查会话中是否存在验证码
        HttpSession session = req.getSession();
        Object sessionSyscodeObj = session.getAttribute("syscode");
        // 验证码不存在或输入的验证码与会话中的验证码不匹配
        if (sessionSyscodeObj == null || !usercode.equalsIgnoreCase(sessionSyscodeObj.toString())) {
            // 验证码错误
            try {
                // 设置错误信息
                req.setAttribute("username", username);
                req.setAttribute("password", password);
                req.setAttribute("usercode", usercode);
                req.setAttribute("msg", "验证码错误");
                // 转发到登录页面
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            } catch (ServletException e) {
                throw new RuntimeException(e);
            }
            return;
        }

        Admins admins = adminsService.login(username, password);
        if (admins != null) {
            // 登录成功，将用户信息保存到session中
            session.setAttribute("username", username);
            //设置session的失效时间
            session.setMaxInactiveInterval(60 * 60);

            // 登录成功，跳转到主页
            try {
                req.getRequestDispatcher("/views/index.jsp").forward(req, resp);
            } catch (ServletException e) {
                throw new RuntimeException(e);
            }
        } else {
            // 登录失败，跳转到错误页面
            //resp.sendRedirect("/views/error.jsp");

            try {
                // 登录失败，提示错误信息
                req.setAttribute("username", username);
                req.setAttribute("password", password);
                req.setAttribute("usercode", usercode);
                req.setAttribute("msg", "用户名或密码错误");
                // 转发到登录页面
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            } catch (ServletException e) {
                throw new RuntimeException(e);
            }
        }
    }


    private static void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 销毁session
        req.getSession().invalidate();
        // 跳转到登录页面
        resp.sendRedirect("/views/login.jsp");
    }
}
